package org.example.controller;

import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Random;

/**
 * @author TonySong
 * @date 2024/4/24 0024
 * @time 15:03
 */
@RestController
@RequestMapping("/person")
public class PersonController {

    @Resource
    private RestTemplate restTemplate;

    @Value("${server.port}")
    private Integer port;

    @Resource
    private DiscoveryClient discoveryClient;

    private ServiceInstance loadBalance(List<ServiceInstance> instances) {
        Random random = new Random();
        //拼接url去调用 ip:port  先自己实现不用ribbon
        ServiceInstance serviceInstance = instances.get(random.nextInt(instances.size()));
        return serviceInstance;
    }
     @GetMapping("/call")
     public String index(){
         List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
         if(instances.size() <= 0){
             System.out.println("没有发现服务");
         }
         ServiceInstance serviceInstance = loadBalance(instances);
         String host = serviceInstance.getHost();
         int port = serviceInstance.getPort();
         String url = "http://" + host + ":" + port + "/hello";
         System.out.println("本次我调用的是" + url);
        return  "Perosn服务的调用"+port+ this.restTemplate.getForObject(url,String.class);
     }

}
